﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleData.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace SimpleData.Infrastructure.Validation
{
	public class EntityValidator
	{

		/// <summary>
		/// Realiza a validação de entidade utilizadas no sistema
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public static EntityValidationResult Validate( object entity )
		{
			ValidationContext context = new ValidationContext( entity, null, null );
			List<ValidationResult> errors = new List<ValidationResult>();

			EntityValidationResult result = new EntityValidationResult( entity );

			if ( Validator.TryValidateObject( entity, context, errors, true ) )
			{
				var messages = ( from e in errors
								 select new EntityValidationResult.MessageItem(
									 new MemberName( e.MemberNames.First() ),
									 e.ErrorMessage ) );

				result.Errors.AddRange( messages );
			}

			return result;
		}
	}

	
}
